<?php

namespace app\common\model;

use fast\Tree;
use think\Exception;
use think\facade\Cache;

/**
 * 地区数据模型.
 */
class Area extends BaseModel
{
    // 表名
    protected $name = 'area';

    /**
     * 根据经纬度获取当前地区信息.
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     *
     * @return Area 城市信息
     */
    public static function getAreaFromLngLat($lng, $lat, $level = 3)
    {
        $namearr = [1 => 'geo:province', 2 => 'geo:city', 3 => 'geo:district'];
        $rangearr = [1 => 5500, 2 => 50, 3 => 20];
        $geoname = isset($namearr[$level]) ? $namearr[$level] : $namearr[3];
        $georange = isset($rangearr[$level]) ? $rangearr[$level] : $rangearr[3];
        // 读取范围内的ID
        $redis = Cache::store('redis')->handler();
        $georadiuslist = [];
        if (method_exists($redis, 'georadius')) {
            $georadiuslist = $redis->georadius($geoname, $lng, $lat, $georange, 'km',
                ['WITHDIST', 'COUNT' => 5, 'ASC']);
        }

        if ($georadiuslist) {
            [$id, $distance] = $georadiuslist[0];
        }
        $id = isset($id) && $id ? $id : 3;

        return self::find($id);
    }

    /**
     * 根据经纬度获取省份.
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     *
     * @return Area
     */
    public static function getProvinceFromLngLat($lng, $lat)
    {
        $provincedata = null;
        $citydata = self::getCityFromLngLat($lng, $lat);
        if ($citydata) {
            $provincedata = self::find($citydata['pid']);
        }

        return $provincedata;
    }

    /**
     * 根据经纬度获取城市
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     *
     * @return Area
     */
    public static function getCityFromLngLat($lng, $lat)
    {
        $citydata = null;
        $districtdata = self::getDistrictFromLngLat($lng, $lat);
        if ($districtdata) {
            $citydata = self::find($districtdata['pid']);
        }

        return $citydata;
    }

    /**
     * 根据经纬度获取地区.
     *
     * @param string $lng 经度
     * @param string $lat 纬度
     *
     * @return Area
     */
    public static function getDistrictFromLngLat($lng, $lat)
    {
        $districtdata = self::getAreaFromLngLat($lng, $lat, 3);

        return $districtdata;
    }


    public function getAreaId($area){
        $arr=explode('/',$area);

        if(count($arr)!=3)
            throw new Exception('请填写完整的所属地信息');

        $province=$this->where(['name'=>$arr[0]])->value('id');
        if(!$province)
            throw new Exception('省份信息错误');

        $city=$this->where(['name'=>$arr[1]])->value('id');
        if(!$city)
            throw new Exception('城市信息错误');

        $county=$this->where(['name'=>$arr[2]])->value('id');
        if(!$county)
            throw new Exception('区县信息错误');


        return [$province,$city,$county];
    }


    public function tree(){
        $ruleList = self::where(['level'=>[1,2]])->order('id', 'asc')->select()->toArray();

        Tree::instance()->init($ruleList);
        $tree = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0),'name',false);

        return $tree;
    }

    public function getTreeList($selected)
    {
        $ruleList = $this->tree();

        $hasChildrens = [];
        foreach ($ruleList as $k => $v) {
            if ($v['haschild']) {
                $hasChildrens[] = $v['id'];
            }
        }
        foreach ($ruleList as $k => $v) {
            $state = ['selected' => in_array($v['id'], $selected) && ! in_array($v['id'], $hasChildrens)];
            $nodeList[] = [
                'id'     => $v['id'],
                'parent' => $v['pid'] ? $v['pid'] : '#',
                'text'   => __($v['name']),
                'type'   => 'menu',
                'state'  => $state,
            ];
        }

        return $nodeList;
    }

    public function getOpenTree(){
        $area_list = self::where(['level'=>[1,2],'open'=>1])->field('id,pid,name,level')->order('level asc,id asc')->select()->toArray();

        $list=[];
        foreach($area_list as $al){
            if($al['level']==1)
                $list[$al['id']]=$al;

            if($al['level']==2)
                $list[$al['pid']]['city'][]=$al;
        }

        return array_values($list);
    }
}
